package com.jhgsys.internal.peccancy.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.constant.DictCodeConstant;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.dict.entity.DictItem;
import com.jhgsys.internal.dict.service.IDictItemService;
import com.jhgsys.internal.dict.service.IDictService;
import com.jhgsys.internal.peccancy.dto.PeccancyClauseRuleDto;
import com.jhgsys.internal.peccancy.entity.PeccancyClause;
import com.jhgsys.internal.peccancy.entity.PeccancyClauseRule;
import com.jhgsys.internal.peccancy.entity.PeccancyClauseRuleRecord;
import com.jhgsys.internal.peccancy.service.IPeccancyClauseRuleRecordService;
import com.jhgsys.internal.peccancy.service.IPeccancyClauseRuleService;
import com.jhgsys.internal.peccancy.service.IPeccancyClauseService;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * 违章条款奖惩规则 Controller
 *
 * @author admin
 * @date 2024-08-08 13:20:28
 */
@Slf4j
@Validated
@Controller
public class PeccancyClauseRuleController extends BaseController {

    @Autowired
    private IPeccancyClauseRuleService peccancyClauseRuleService;

    @Autowired
    private IPeccancyClauseRuleRecordService recordService;

    @Autowired
    private IPeccancyClauseService clauseService;

    @Autowired
    private IDictService dictService;


    @GetMapping(FebsConstant.VIEW_PREFIX + "peccancyClauseRule")
    @RequiresPermissions("peccancyClauseRule:view")
    public String peccancyClauseRuleIndex(Model model){
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        model.addAttribute("disposeFormList", dictService.findDictByCode(DictCodeConstant.SAFETY_PECCANCY_DISPOSE_FORM));
        return jumpPage("peccancy/peccancyClauseRule/peccancyClauseRuleList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "peccancyClauseRule/add")
    @RequiresPermissions("peccancyClauseRule:add")
    public String peccancyClauseRuleAdd(){
        return jumpPage("peccancy/peccancyClauseRule/peccancyClauseRuleEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "peccancyClauseRule/update/{id}")
    @RequiresPermissions("peccancyClauseRule:edit")
    public String peccancyClauseRuleUpdate(Model model, @PathVariable("id") String id){
        PeccancyClauseRuleDto dto = new PeccancyClauseRuleDto();
        PeccancyClauseRule rule = peccancyClauseRuleService.findPeccancyClauseRuleById(id);
        BeanUtils.copyProperties(rule,dto);
        PeccancyClause cause = clauseService.findPeccancyClauseById(rule.getClauseId());
        dto.setClauseName(cause.getClauseName());
        model.addAttribute("peccancyClauseRule",dto );
        return jumpPage("peccancy/peccancyClauseRule/peccancyClauseRuleEdit");
    }

    /**
     * 查询（所有）
     * @author admin
     * @date 2024-08-08 13:20:28
     */
    @GetMapping("peccancyClauseRule")
    @ResponseBody
    @RequiresPermissions("peccancyClauseRule:view")
    public FebsResponse getAllPeccancyClauseRules(PeccancyClauseRule peccancyClauseRule) {
        return new FebsResponse().success().data(peccancyClauseRuleService.findPeccancyClauseRuleList(peccancyClauseRule));
    }

    /**
     * 查询（分页）
     * @author admin
     * @date 2024-08-08 13:20:28
     */
    @GetMapping("peccancyClauseRule/listByClauseId")
    @ResponseBody
    @RequiresPermissions("peccancyClauseRule:view")
    public FebsResponse peccancyClauseRuleListByClauseId(QueryRequest request, PeccancyClauseRule peccancyClauseRule) {
        IPage<PeccancyClauseRule> page = this.peccancyClauseRuleService.findPeccancyClauseRulePage(request, peccancyClauseRule);
        Map<String, Object> dataTable = getDataTable(page);
        return new FebsResponse().success().data(dataTable);
    }

//    /**
//     * 查询（分页）
//     * @author admin
//     * @date 2024-08-08 13:20:28
//     */
//    @GetMapping("peccancyClauseRule/list")
//    @ResponseBody
//    @RequiresPermissions("peccancyClauseRule:view")
//    public FebsResponse peccancyClauseRuleList(QueryRequest request, PeccancyClauseRule peccancyClauseRule) {
//        peccancyClauseRule.setClauseId("#");
//        Map<String, Object> dataTable = getDataTable(this.peccancyClauseRuleService.findPeccancyClauseRulePage(request, peccancyClauseRule));
//        return new FebsResponse().success().data(dataTable);
//    }

    /**
     * 新增 PeccancyClauseRule
     * @author admin
     * @date 2024-08-08 13:20:28
     */
    @Log("新增PeccancyClauseRule")
    @PostMapping("peccancyClauseRule")
    @ResponseBody
    @RequiresPermissions("peccancyClauseRule:add")
    public FebsResponse addPeccancyClauseRule(@RequestBody PeccancyClauseRule peccancyClauseRule) throws FebsException {

        try {
            checkParams(peccancyClauseRule);
            PeccancyClauseRule queryData = new PeccancyClauseRule();
            queryData.setClauseNo(peccancyClauseRule.getClauseNo());
            List<PeccancyClauseRule> listData = this.peccancyClauseRuleService.findPeccancyClauseRuleList(queryData);
            if(!CollectionUtils.isEmpty(listData)){
                return new FebsResponse().fail().message("条款书编号已存在！");
            }
            peccancyClauseRule.setCreatedBy(getCurrentUser().getUserName());
            this.peccancyClauseRuleService.createPeccancyClauseRule(peccancyClauseRule);
            PeccancyClauseRuleRecord record = new PeccancyClauseRuleRecord();
            record.setClauseRuleId(peccancyClauseRule.getClauseRuleId());
            record.setCreatedBy(getCurrentUser().getUserName());
            record.setChangeTime(new Date());
            record.setAfterJson(JSON.toJSONString(peccancyClauseRule));
            record.setChangeType("1");
            recordService.createPeccancyClauseRuleRecord(record);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增PeccancyClauseRule失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 逻辑删除 PeccancyClauseRule
     * @author admin
     * @date 2024-08-08 13:20:28
     */
    @Log("逻辑删除PeccancyClauseRule")
    @GetMapping("peccancyClauseRule/delete/{id}")
    @ResponseBody
    @RequiresPermissions("peccancyClauseRule:delete")
    public FebsResponse deletePeccancyClauseRule(@PathVariable("id") String peccancyClauseRuleIds) throws FebsException {
        try {
            PeccancyClauseRule peccancyClauseRule = new PeccancyClauseRule();
            peccancyClauseRule.setDeletedBy(getCurrentUser().getUserName());
            peccancyClauseRule.setDeletedTime(new Date());
            peccancyClauseRule.setDeletedFlg(FebsConstant.INVALID);
            this.peccancyClauseRuleService.deletePeccancyClauseRule(peccancyClauseRule,peccancyClauseRuleIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除PeccancyClauseRule失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
    * 物理删除 PeccancyClauseRule
    * @author admin
    * @date 2024-08-08 13:20:28
    */
    @Log("物理删除PeccancyClauseRule")
    @GetMapping("peccancyClauseRule/physicallyDelete/{id}")
    @ResponseBody
    @RequiresPermissions("peccancyClauseRule:delete")
    public FebsResponse physicallyDeletePeccancyClauseRule(@PathVariable("id") String peccancyClauseRuleIds) throws FebsException {
        try {
            this.peccancyClauseRuleService.physicallyDeletePeccancyClauseRule(peccancyClauseRuleIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除PeccancyClauseRule失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 修改 PeccancyClauseRule
     * @author admin
     * @date 2024-08-08 13:20:28
     */
    @Log("修改PeccancyClauseRule")
    @PostMapping("peccancyClauseRule/updateStatus")
    @ResponseBody
    @RequiresPermissions("peccancyClauseRule:edit")
    public FebsResponse updateStatusPeccancyClauseRule(@RequestBody PeccancyClauseRule peccancyClauseRule) throws FebsException {
        try {
            if(StringUtils.isBlank(peccancyClauseRule.getClauseRuleId())){
                return new FebsResponse().fail().message("条款书ID不能为空");
            }
            if(StringUtils.isBlank(peccancyClauseRule.getStatus())){
                return new FebsResponse().fail().message("条款状态不能为空");
            }

            peccancyClauseRule.setUpdatedBy(getCurrentUser().getUserName());
            this.peccancyClauseRuleService.updatePeccancyClauseRule(peccancyClauseRule);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改PeccancyClauseRule失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 修改 PeccancyClauseRule
     * @author admin
     * @date 2024-08-08 13:20:28
     */
    @Log("修改PeccancyClauseRule")
    @PostMapping("peccancyClauseRule/update")
    @ResponseBody
    @RequiresPermissions("peccancyClauseRule:edit")
    public FebsResponse updatePeccancyClauseRule(@RequestBody PeccancyClauseRule peccancyClauseRule) throws FebsException {

        try {
            checkParams(peccancyClauseRule);
            if(StringUtils.isBlank(peccancyClauseRule.getClauseRuleId())){
                return new FebsResponse().fail().message("条款书ID不能为空");
            }
            PeccancyClauseRule queryData = new PeccancyClauseRule();
            queryData.setClauseNo(peccancyClauseRule.getClauseNo());
            List<PeccancyClauseRule> listData = this.peccancyClauseRuleService.findPeccancyClauseRuleList(queryData);
            if(!CollectionUtils.isEmpty(listData) && !peccancyClauseRule.getClauseRuleId().equals(listData.get(0).getClauseRuleId())){
                return new FebsResponse().fail().message("条款书编号已存在！");
            }
            PeccancyClauseRule oldRule = this.peccancyClauseRuleService.findPeccancyClauseRuleById(peccancyClauseRule.getClauseRuleId());
            peccancyClauseRule.setUpdatedBy(getCurrentUser().getUserName());
            this.peccancyClauseRuleService.updatePeccancyClauseRule(peccancyClauseRule);
            PeccancyClauseRuleRecord record = new PeccancyClauseRuleRecord();
            record.setClauseRuleId(peccancyClauseRule.getClauseRuleId());
            record.setCreatedBy(getCurrentUser().getUserName());
            record.setChangeTime(new Date());
            record.setAfterJson(JSON.toJSONString(peccancyClauseRule));
            record.setBeforeJson(JSON.toJSONString(oldRule));
            record.setChangeType("2");
            recordService.createPeccancyClauseRuleRecord(record);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改PeccancyClauseRule失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 导出 PeccancyClauseRule的excel
     * @author admin
     * @date 2024-08-08 13:20:28
     */
    @PostMapping("peccancyClauseRule/excel")
    @ResponseBody
    @RequiresPermissions("peccancyClauseRule:view")
    public void export(QueryRequest queryRequest, PeccancyClauseRule peccancyClauseRule, HttpServletResponse response) throws FebsException {
        try {
            List<PeccancyClauseRule> peccancyClauseRules = this.peccancyClauseRuleService.findPeccancyClauseRulePage(queryRequest, peccancyClauseRule).getRecords();
            ExcelKit.$Export(PeccancyClauseRule.class, response).downXlsx(peccancyClauseRules, false);
        } catch (Exception e) {
            String message = "导出Excel失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    private void checkParams(PeccancyClauseRule peccancyClauseRule) throws FebsException {
        if(StringUtils.isBlank(peccancyClauseRule.getTenantId())){
            throw new FebsException("所属公司不能为空");
        }
        if(StringUtils.isBlank(peccancyClauseRule.getClauseId())){
            throw new FebsException("违章条款Id不能为空");
        }
        if(StringUtils.isBlank(peccancyClauseRule.getClauseNo())){
            throw new FebsException("条款号不能为空");
        }
        if(ObjectUtils.isEmpty(peccancyClauseRule.getClauseLevel())){
            throw new FebsException("条款等级不能为空");
        }
        if(StringUtils.isBlank(peccancyClauseRule.getDisposeForm())){
            throw new FebsException("处理形式不能为空");
        }

        if(ObjectUtils.isEmpty(peccancyClauseRule.getReferenceMoney())){
            throw new FebsException("奖惩金额不能为空");
        }
        if(ObjectUtils.isEmpty(peccancyClauseRule.getExamineScore())){
            throw new FebsException("考核分数不能为空");
        }
        if(StringUtils.isBlank(peccancyClauseRule.getClauseContent())){
            throw new FebsException("条款内容不能为空");
        }
        if(ObjectUtils.isEmpty(peccancyClauseRule.getExecuteDate())){
            throw new FebsException("执行时间不能为空");
        }
        if(StringUtils.isBlank(peccancyClauseRule.getStatus())){
            throw new FebsException("有效状态不能为空");
        }
    }
}
